package com.wuax.service.impl;

import cn.hutool.core.util.IdUtil;
import com.wuax.domain.BookType;
import com.wuax.domain.vo.BookVo;
import com.wuax.domain.vo.LayTableData;
import com.wuax.domain.vo.Result;
import com.wuax.mapper.BookMapper;
import com.wuax.mapper.BookTypeMapper;
import com.wuax.service.BookTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookTypeServiceImpl implements BookTypeService {

    @Autowired
    private BookTypeMapper bookTypeMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public LayTableData list(BookType bookType) {
        // 获取总条数
        int i = bookTypeMapper.selectCount(bookType);
        // 获取分类数据并封装成laytable所需格式
        return new LayTableData(i, bookTypeMapper.select(bookType));
    }

    @Override
    public Result add(BookType bookType) {
        // 生成uuid
        bookType.setBookTypeId(IdUtil.simpleUUID());
        // 插入数据
        return bookTypeMapper.insert(bookType) == 1 ? Result.success("添加成功") : Result.error("添加失败");
    }

    @Override
    public Result update(BookType bookType) {
        // 不更新创建时间
        bookType.setCreateDate(null);
        // g更新数据
        return bookTypeMapper.update(bookType) == 1 ? Result.success("修改成功") : Result.error("修改失败");
    }

    @Override
    public Result batchDelete(List<String> bookTypeIds) {
        // 循环查询当前分类下有没有图书，如果有的话返回错误，不能删除
        for (String bookTypeId : bookTypeIds) {
            // 查询当前的分类下的图书
            List<BookVo> list = bookMapper.selectByTypeId(bookTypeId);
            // 判断
            if (list != null && list.size() > 0) {
                return Result.error("当前分类下有图书存在，不能删除");
            }
        }
        // 批量删除
        return bookTypeMapper.batchDelete(bookTypeIds) > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }

    @Override
    public Result listAll() {
        // 获取所有的分类
        return Result.success(bookTypeMapper.select(new BookType()));
    }
}
